package org.zanpu.timer.SpringRest.impl;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.zanpu.timer.SpringRest.interf.HttpRestInf;

import java.util.Map;

/**
 * Rest请求接口
 * Created by MD on 2016/12/23.
 */
@Service("httpRest")
public class HttpRest implements HttpRestInf {


    @Qualifier("restTemplate")
    @Autowired
    private RestTemplate restTemplate;

    HttpHeaders headers;

    HttpRest() {
        headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/text;charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
    }

    /**
     * 无参GET请求
     *
     * @param url 接口地址
     * @return Object
     */
    public String get(String url) throws Exception {
        try {
            String result = restTemplate.getForObject(url, String.class);
            return result;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

    }

    /**
     * 有参GET请求
     *
     * @param url          接口地址
     * @param uriVariables 参数Map
     * @return Object
     */
    public String get(String url, Map<String, String> uriVariables) throws Exception {
        try {
            if (uriVariables != null) {
                if (!uriVariables.isEmpty()) {
                    StringBuilder sb = new StringBuilder("?1=1");
                    uriVariables.keySet().parallelStream().forEach(key -> sb.append("&").append(key).append("={").append(key).append("}"));
                    url += sb.toString();
                }
            }

            String result = restTemplate.getForObject(url, String.class, uriVariables);
            return result;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * POST请求
     * @param url       接口地址
     * @param variables json参数对象
     * @return Object
     */
    public String post(String url, JSONObject variables) throws Exception {
        try {
            String result = restTemplate.postForObject(url, new HttpEntity<>(
                    variables == null ? null : variables.toString(), headers), String.class);
            return result;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

    }
}
